//
//  CLModifyPasswordViewController.m
//  CarLifes
//
//  Created by yu on 2017/6/26.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "ModifyPsdViewController.h"

#import "ModifyPasswordCell.h"
#import "EquipmentModel.h"
#import "TabBarController.h"
#import "UIView+TransitionAnimation.h"

#define kModifyPasswordCellId @"ModifyPasswordCell"

@interface ModifyPsdViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, assign) LoginType loginType;

@end

@implementation ModifyPsdViewController

- (void)setTableView:(UITableView *)tableView
{
    _tableView = tableView;
    if (@available(iOS 13.0, *)) {
        UIColor *bgColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBackGroundLightGrayColor;
            } else {
                return UIColor.systemBackgroundColor;
            }
        }];
        _tableView.backgroundColor = bgColor;
    } else {
        _tableView.backgroundColor = kBackGroundLightGrayColor;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"修改密码";
    
    self.loginType = self.user.loginType;
    
    [self.tableView registerNib:NIB_NAMED(kModifyPasswordCellId) forCellReuseIdentifier:kModifyPasswordCellId];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ModifyPasswordCell *cell = [tableView dequeueReusableCellWithIdentifier:kModifyPasswordCellId];
    cell.label.text = _titleArray[indexPath.row];
    cell.textField.placeholder = _titleArray[indexPath.row];
    cell.textField.tag = indexPath.row + 1;
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
    headerView.tintColor = [UIColor clearColor];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 100;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor clearColor];
    
    UILabel *noteLabel = [[UILabel alloc] init];
    noteLabel.text = @"请设置6至8位有效密码";
    noteLabel.textColor = [UIColor lightGrayColor];
    noteLabel.font = SYSTEM_FONT(12);
    [bgView addSubview:noteLabel];
    
    UIButton *submitButton = [[UIButton alloc] init];
    if (@available(iOS 13.0, *)) {
        UIColor *submitColor = [UIColor colorWithDynamicProvider:^UIColor * _Nonnull(UITraitCollection * _Nonnull traitCollection) {
            if (traitCollection.userInterfaceStyle == UIUserInterfaceStyleLight) {
                return kBaseColor;
            } else {
                return kBaseColorDark;
            }
        }];
        submitButton.backgroundColor = submitColor;
    } else {
        submitButton.backgroundColor = kBaseColor;
    }
    [submitButton setTitle:@"提交" forState:UIControlStateNormal];
    [submitButton addTarget:self action:@selector(submitAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:submitButton];
    
    noteLabel.sd_layout
    .topSpaceToView(bgView, 10)
    .leftSpaceToView(bgView, 15)
    .rightSpaceToView(bgView, 15)
    .autoHeightRatio(0);
    
    submitButton.sd_layout
    .leftEqualToView(noteLabel)
    .rightEqualToView(noteLabel)
    .bottomEqualToView(bgView)
    .heightIs(45);
    
    return bgView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)submitAction
{
    UITextField *oldPsd = [self.tableView viewWithTag:1];
    UITextField *newPsd = [self.tableView viewWithTag:2];
    UITextField *confirmPsd = [self.tableView viewWithTag:3];
    [oldPsd resignFirstResponder];
    [newPsd resignFirstResponder];
    [confirmPsd resignFirstResponder];
    
    if (self.loginType == LoginTypeAccount) {
        // 修改帐号登录密码
        // 帐号
        NSString *psd = self.user.password;
        
        if (!(oldPsd.text.length >= 6 && oldPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位原始密码"];
            return;
        }
        
        if (!(newPsd.text.length >= 6 && newPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位新密码"];
            return;
        }
        
        if (!(confirmPsd.text.length >= 6 && confirmPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位确认密码"];
            return;
        }
        
        if (![psd isEqualToString:oldPsd.text]) {
            [MBProgressHUD showToast:@"原始密码输入错误"];
            return;
        }
        
        if ([newPsd.text isEqualToString:psd]) {
            [MBProgressHUD showToast:@"新密码不能与原始密码一致"];
            return;
        }
        
        if (![newPsd.text isEqualToString:confirmPsd.text]) {
            [MBProgressHUD showToast:@"新密码与确认密码不一致"];
            return;
        }
        
        [self.requestTool changeAccPsd:newPsd.text isSavePsd:YES success:^{
            PPLog(@"修改密码成功");
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"密码修改成功，请重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                TabBarController *tab = [[TabBarController alloc] init];
                [KEY_WINDOW addTransitionAnimationWithDuration:0.5f type:TransitionCube subType:FROM_BOTTOM];
                KEY_WINDOW.rootViewController = tab;
            }]];
            [self presentViewController:alertController animated:YES completion:nil];
        } failure:^(NSString *error) {
            PPLog(@"modify psd error = %@",error);
        }];
    } else {// 修改车架号登录密码
        
        NSString *psd = self.user.vinPassword;
        
        if (!(oldPsd.text.length >= 6 && oldPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位原始密码"];
            return;
        }
        
        if (!(newPsd.text.length >= 6 && newPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位新密码"];
            return;
        }
        
        if (!(confirmPsd.text.length >= 6 && confirmPsd.text.length <= 8)) {
            [MBProgressHUD showToast:@"请输入6至8位确认密码"];
            return;
        }
        
        if (![psd isEqualToString:oldPsd.text]) {
            [MBProgressHUD showToast:@"原始密码输入错误"];
            return;
        }
        
        if ([newPsd.text isEqualToString:psd]) {
            [MBProgressHUD showToast:@"新密码不能与原始密码一致"];
            return;
        }
        
        if (![newPsd.text isEqualToString:confirmPsd.text]) {
            [MBProgressHUD showToast:@"新密码与确认密码不一致"];
            return;
        }
        
        for (EquipmentModel *eModel in self.dataSource) {
            [self.requestTool changeVinPsd:newPsd.text eqId:eModel.eqId success:^{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"密码修改成功，请重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self.navigationController popToRootViewControllerAnimated:YES];
                }]];
                [self presentViewController:alertController animated:YES completion:nil];
            } failure:^(NSString *error) {
                PPLog(@"modify psd error = %@",error);
            }];
        }
    }
}

- (NSArray *)titleArray {
    if (!_titleArray) {
        _titleArray = @[@"原始密码",@"新 密 码",@"确认密码"];
    }
    return _titleArray;
}

@end
